package com.snoob.springcloudalibaba.util;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

;

/**
 * @描述: 验证码工具类
 * @作者: lixing lixing_java@163.com
 * @日期 2019/10/10 21:34
 */
public class VerifyCodeUtil {
    private int lineCount = 50; // 验证码干扰线数
    private String verifyCodes = "23456789abcdefghjkmnprstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; // 验证码来源
    private static Random random = new Random();

    /**
     * @描述 随机生成验证码
     * @作者 lixing
     * @日期 2019/10/27 22:40
     * @Param [verifyCodeSize 验证码长度, verifyCodeSources 验证码来源]
     * @return java.lang.String
     */
    public String generateVerifyCode(int verifyCodeSize, String verifyCodeSources) {
        if (verifyCodeSources == null || verifyCodeSources.length() == 0) {
            verifyCodeSources = verifyCodes;
        }
        int codesLen = verifyCodeSources.length();
        Random rand = new Random( System.currentTimeMillis() );
        StringBuilder verifyCode = new StringBuilder( verifyCodeSize );
        for (int i = 0; i < verifyCodeSize; i++) {
            verifyCode.append( verifyCodeSources.charAt( rand.nextInt( codesLen - 1 ) ) );
        }
        return verifyCode.toString();
    }

    /**
     * 输出验证码图片到流媒体
     *
     * @param verifyCode         验证码内容
     * @param verifyCodeLength   验证码长度
     * @param width        宽度
     * @param height       高度
     * @param servletOutputStream 字节输出流
     * @throws IOException
     */
    public void outputImage_1(String verifyCode, int verifyCodeLength, int width, int height, ServletOutputStream servletOutputStream) throws IOException {
        int x; //字符所在x坐标
        int fontHeight; //字体高度
        int codeY; //字符所在y坐标
        int red;
        int green;
        int blue;
        x = width / (verifyCodeLength + 2);
        fontHeight = height - 2;
        codeY = height - 4;
        BufferedImage bufferedImage = new BufferedImage( width, height, BufferedImage.TYPE_INT_BGR );
        Graphics2D graphics2D = bufferedImage.createGraphics();
        Random random = new Random();
        graphics2D.setColor( Color.WHITE );
        graphics2D.fillRect( 0, 0, width, height );
        Font font = new Font( "Fixedays", Font.PLAIN, fontHeight );
        graphics2D.setFont( font );
        for (int i = 0; i < lineCount; i++) {
            //x轴第一个点的位置
            int x1 = random.nextInt( width );
            //y轴第一个点的位置
            int y1 = random.nextInt( height );
            //x轴第二个点的位置
            int x2 = x1 + random.nextInt( width >> 2 );
            //y轴第二个点的位置
            int y2 = y1 + random.nextInt( height >> 2 );
            red = random.nextInt( 255 );
            green = random.nextInt( 255 );
            blue = random.nextInt( 255 );
            graphics2D.setColor( new Color( red, green, blue ) );
            graphics2D.drawLine( x1, y1, x2, y2 );
        }
        for (int i = 0; i < verifyCodeLength; i++) {
            red = random.nextInt( 255 );
            green = random.nextInt( 255 );
            blue = random.nextInt( 255 );
            graphics2D.setColor( new Color( red, green, blue ) );
            graphics2D.drawString( verifyCode.substring( i, i + 1 ), (i + 1) * x, codeY );
        }

        ImageIO.write( bufferedImage, "jpg", servletOutputStream );
    }

    /**
     * 输出验证码图片到流媒体
     *
     * @param verifyCode         验证码内容
     * @param width        宽度
     * @param height       高度
     * @param servletOutputStream 字节输出流
     * @throws IOException
     */
    public static void outputImage_2(String verifyCode, int width, int height, ServletOutputStream servletOutputStream) throws IOException {
        int verifySize = verifyCode.length();
        BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW};
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt( colorSpaces.length )];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort( fractions );

        g2.setColor( Color.GRAY );// 设置边框色
        g2.fillRect( 0, 0, width, height );

        Color c = getRandColor( 200, 250 );
        g2.setColor( c );// 设置背景色
        g2.fillRect( 0, 2, width, height - 4 );

        // 绘制干扰线
        Random random = new Random();
        g2.setColor( getRandColor( 160, 200 ) );// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt( width - 1 );
            int y = random.nextInt( height - 1 );
            int xl = random.nextInt( 6 ) + 1;
            int yl = random.nextInt( 12 ) + 1;
            g2.drawLine( x, y, x + xl + 40, y + yl + 20 );
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt( width );
            int y = random.nextInt( height );
            int rgb = getRandomIntColor();
            image.setRGB( x, y, rgb );
        }

        shear( g2, width, height, c );// 使图片扭曲

        g2.setColor( getRandColor( 100, 160 ) );
        int fontSize = height - 4;
        Font font = new Font( "楷体", Font.BOLD, fontSize );
        g2.setFont( font );
        char[] chars = verifyCode.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(
                    Math.PI / 4 * rand.nextDouble()
                            * (rand.nextBoolean() ? 1 : -1), (width / verifySize)
                            * i + fontSize / 2, height / 2 );
            g2.setTransform( affine );
            g2.drawChars( chars, i, 1, ((width - 10) / verifySize) * i + 5, height / 2
                    + fontSize / 2 - 5 );
        }
        g2.dispose();
        ImageIO.write( image, "jpg", servletOutputStream );
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt( bc - fc );
        int g = fc + random.nextInt( bc - fc );
        int b = fc + random.nextInt( bc - fc );
        return new Color( r, g, b );
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt( 255 );
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX( g, w1, h1, color );
        shearY( g, w1, h1, color );
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {
        int period = random.nextInt( 2 );
        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt( 2 );

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin( (double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames );
            g.copyArea( 0, i, w1, 1, (int) d, 0 );
            if (borderGap) {
                g.setColor( color );
                g.drawLine( (int) d, i, 0, i );
                g.drawLine( (int) d + w1, i, w1, i );
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {
        int period = random.nextInt( 40 ) + 10; // 50;
        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin( (double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames );
            g.copyArea( i, 0, 1, h1, 0, (int) d );
            if (borderGap) {
                g.setColor( color );
                g.drawLine( i, (int) d, i, 0 );
                g.drawLine( i, (int) d + h1, i, h1 );
            }
        }
    }

}
